<template>

  <div class="app-container">

    <!-- 过滤搜索框 START-->
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 150px;" class="filter-item" placeholder="姓名" v-model="filter.columns.name">
      </el-input>
      <el-select clearable style="width: 80px" class="filter-item" v-model="filter.columns.sex" placeholder="性别">
        <el-option label="女" value="0"></el-option>
        <el-option label="男" value="1"></el-option>
      </el-select>
      <el-select clearable style="width: 120px" class="filter-item" @change="handleFilter" v-model="filter.columns.type" placeholder="审核状态">
        <el-option label="未审核" value="0"></el-option>
        <el-option label="审核通过" value="1"></el-option>
        <el-option label="审核不通过" value="2"></el-option>
      </el-select>
      <el-select clearable style="width: 140px" class="filter-item" v-model="listQuery.sorts[0]">
        <el-option label="ID正序" value="+id"></el-option>
        <el-option label="ID倒序" value="-id"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">导出</el-button>
      <el-upload class="filter-item" multiple :headers="tokenHeader" :action="importFileUrl" :data="upLoadData" name="file" :onError="uploadError" :onSuccess="uploadSuccess">
        <el-button type="primary">上传文件
          <i class="el-icon-upload el-icon--right"></i>
        </el-button>
      </el-upload>
      <el-button class="filter-item" type="danger" v-waves icon="el-icon-delete" @click="handleDeleteMulti">批量删除</el-button>
    </div>
    <!-- 过滤搜索框 END -->

    <!-- 表格呈现 START -->
    <el-table ref="demoTable" @selection-change="handleSelectionChange" element-loading-text="加载中" v-loading="listLoading" fit highlight-current-row border :data="list">
      <el-table-column prop="index" type="index"></el-table-column>
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="姓名" width="80">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>姓名: {{ scope.row.name }}</p>
            <p>住址: {{ scope.row.address }}</p>
            <div slot="reference" class="name-wrapper">
              {{ scope.row.name }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="sex" align="center" label="性别" width="70" :filter-method="filterSex" :filters="[{ text: '女', value: '女' }, { text: '男', value: '男' }]"></el-table-column>
      <el-table-column label="审核状态" width="110">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type | typeFilter">{{scope.row.type}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="birthday" align="center" label="生日" sortable width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.birthday }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column type="expand" label="详情" width="80">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="ID">
              <span>{{ props.row.id }}</span>
            </el-form-item>
            <el-form-item label="姓名">
              <span>{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item label="住址">
              <span>{{ props.row.address }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格呈现 END -->

    <!-- 分页导航栏 START -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10, 25, 50, 100]" :pager-count="11" :total="total" layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 分页导航栏 END -->

    <!-- 编辑信息弹出框 START -->
    <el-dialog :title="dialogTitle[dialogStatus]" :visible.sync="dialogVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px">
        <el-form-item label="生日" prop="birthday">
          <el-date-picker format="yyyy-MM-dd" value-format="yyyy-MM-dd" v-model="temp.birthday" type="date" placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" placeholder="请输入姓名" max="5"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="temp.sex" placeholder="请选择性别">
            <el-option key="男" label="男" value="男"> </el-option>
            <el-option key="女" label="女" value="女"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="type">
          <el-select v-model="temp.type" placeholder="请选择审核状态">
            <el-option key="未审核" label="未审核" value="未审核"> </el-option>
            <el-option key="审核通过" label="审核通过" value="审核通过"> </el-option>
            <el-option key="审核不通过" label="审核不通过" value="审核不通过"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input max="11" placeholder="请输入手机号" v-model.number="temp.phone">
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="temp.email">
          </el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入地址" v-model="temp.address">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :disabled="dialogLoading" v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button :disabled="dialogLoading" v-else type="primary" @click="updateData">修改</el-button>
      </div>
    </el-dialog>
    <!-- 编辑信息弹出框 END -->

  </div>
</template>

<script>
import apiDemo from '@/api/demo/demo.js'
import waves from '@/directive/waves' // 水波纹特效 指令
import { getToken } from '@/utils/auth'

export default {
  name: 'demo',
  components: {},
  directives: { waves },
  data() {
    return {
      importFileUrl: process.env.BASE_API + '/file/upload',
      upLoadData: {
        path: 'test'
      },
      downloadLoading: false,
      total: 0,
      // 临时对象,用于编辑修改操作
      temp: {},
      // 弹出框表单状态
      dialogStatus: undefined,
      dialogTitle: {
        create: '创建Demo',
        update: '修改Demo'
      },
      dialogVisible: false,
      dialogLoading: false,
      // 编辑框校验规则
      rules: {
        name: [
          { required: true, message: '名字不能为空', trigger: 'change' },
          { min: 1, max: 25, message: '长度在 1 到 25 个字符' },
          { pattern: /^[\u4E00-\u9FA5]+$/, message: '用户名只能为中文', trigger: 'blur' }
        ],
        birthday: [{ required: true, message: '生日必填', trigger: 'change' }],
        sex: [{ required: true, message: '性别必填', trigger: 'change' }],
        email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
        phone: [
          { pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码' },
          { required: true, message: '手机号必填', trigger: 'change' }
        ]
      },
      list: [],
      listLoading: true,
      // 查询条件
      listQuery: {
        page: 1,
        size: 10,
        sorts: [],
        columns: {}
      },
      // 过滤框条件
      filter: {
        columns: {
          name: undefined,
          sex: undefined,
          type: undefined
        }
      },
      // 多选框选中对象
      multipleSelection: []
    }
  },
  watch: {
    listQuery: {
      handler(val) {
        this.getData(val)
      },
      deep: true
    }
  },
  filters: {
    typeFilter(type) {
      const typeMap = {
        '未审核': 'info',
        '审核通过': 'success',
        '审核不通过': 'danger'
      }
      return typeMap[type]
    }
  },
  methods: {
    // 上传成功后的回调
    uploadSuccess(response, file, fileList) {
      this.$notify({ title: '成功', message: '上传成功', type: 'success', duration: 2000 })
    },
    // 上传错误
    uploadError(response, file, fileList) {
      this.$notify({ title: '失败', message: '上传失败', type: 'error', duration: 2000 })
    },
    // 上传前对文件的大小的判断
    beforeAvatarUpload(file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const extension3 = file.name.split('.')[1] === 'doc'
      const extension4 = file.name.split('.')[1] === 'docx'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!extension && !extension2 && !extension3 && !extension4) {
        console.log('上传模板只能是 xls、xlsx、doc、docx 格式!')
      }
      if (!isLt2M) {
        console.log('上传模板大小不能超过 10MB!')
      }
      return extension || extension2 || extension3 || extension4 && isLt2M
    },
    filterSex(value, row) {
      return row.sex === value
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.dialogLoading = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        type: '未审核',
        sex: undefined,
        phone: undefined,
        email: undefined,
        address: undefined
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogLoading = true
          apiDemo.create(this.temp).then(res => {
            this.dialogLoading = false
            // 状态为成功
            if (res.status === 200) {
              this.dialogVisible = false
              // 数据直接插入表格顶部
              this.list.unshift(this.temp)
              this.$notify({ title: '成功', message: '创建成功', type: 'success', duration: 2000 })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogLoading = false
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      // 复制对象
      const tempData = Object.assign({}, this.temp)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogLoading = true
          apiDemo.update(tempData).then(res => {
            this.dialogLoading = false
            if (res.status === 200) {
              this.dialogVisible = false
              this.$notify({ title: '成功', message: '更新成功', type: 'success', duration: 2000 })
              // 将修改后的对象替换进列表中
              for (const item of this.list) {
                if (item.id === this.temp.id) {
                  const index = this.list.indexOf(item)
                  this.list.splice(index, 1, tempData)
                  break
                }
              }
            }
          })
        }
      })
    },
    handleDelete(row) {
      apiDemo.remove(row).then(res => {
        if (res.status === 200) {
          this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        }
      })
    },
    handleDeleteMulti() {
      const rows = this.multipleSelection
      const params = Array(0)
      rows.forEach(row => {
        params.push(row.id)
      })

      if (params.length > 0) {
        apiDemo.removeMulti(params).then(res => {
          if (res.status === 200) {
            this.$message({
              message: res.data,
              type: 'success'
            })
            rows.forEach(row => {
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
          }
        })
      } else {
        this.$message({
          message: '请先勾选列表',
          type: 'warning'
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },
    handleSizeChange(size) {
      this.listQuery.size = size
    },
    handleCurrentChange(page) {
      this.listQuery.page = page
    },
    getData() {
      this.listLoading = true
      apiDemo.search(this.listQuery).then(res => {
        this.listLoading = false
        if (res.status === 200) {
          this.list = res.data.list
          this.total = res.data.total
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.columns = JSON.parse(JSON.stringify(this.filter.columns))
      this.getData()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['sex', 'type', 'name', 'birthday', 'email', 'phone']
        const filterVal = ['sex', 'type', 'name', 'birthday', 'email', 'phone']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        // 字段的格式处理
        return v[j]
      }))
    }
  },
  computed: {
    tokenHeader: function() {
      return { 'X-token': getToken() }
    }
  },
  created: function() {
    this.getData(this.listQuery)
  },
  mounted: function() {
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

</style>
